<template>
    <div class="file">
        <div class="filea">
            <span class="font">请上传Excel文件:</span>
            <el-form label-width="80px" class="demo-ruleForm">
                <el-form-item>
                    <el-upload action="" :http-request="upload" :before-upload="beforeUploadFile"  ref="upload" >
                        <el-button type="success" plain  class="shangchuan">上传文件<i class="el-icon-upload2"></i></el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <div class="daochu">
            <div class="daochu1"><el-button type="primary" plain @click="generateOrderReport(1)">导出主品报表</el-button></div>
            <div class="daochu2"><el-button type="primary" plain @click="generateOrderReport(2)">导出媒体销量表</el-button></div>
            <div class="daochu1"><el-button type="primary" plain @click="generateOrderReport(3)">导出每日飘线及合计销量表</el-button></div>
            <!-- <div class="daochu3"><el-button type="primary" plain @click="generateMainProductReport(5)">导出主表监控飘线表</el-button></div> -->
            <!-- <div class="daochu1"><el-button type="primary" plain @click="generateMainProductReport(6)">导出非活动区域飘线表</el-button></div> -->
            <!-- <div class="daochu1"><el-button type="primary" plain @click="generateMainProductReport(7)">导出历史飘线表</el-button></div> -->
            <!-- <div class="daochu1"><el-button type="primary" plain @click="generateMainProductReport(8)">导出爱听团队表</el-button></div> -->
            <!-- <div class="daochu1"><el-button type="primary" plain @click="generateMainProductReport()">导出纯飘线表</el-button></div> -->
            <!-- <div class="daochu1"><el-button type="primary" plain @click="generateMainProductReport(10)">导出二级页表</el-button></div> -->
            <!-- <div class="daochu1"><el-button type="primary" plain @click="generateMainProductReport(4)">导出副品销量表</el-button></div> -->
        </div>
    </div>
    <div class="riqi1" @keyup.enter="keyDown($event)">
        <span class="demonstration"  style="width:470px;">付款时间:</span>
        <el-date-picker v-model="startDate" type="date" placeholder="开始日期" style="width:100%;"></el-date-picker>
        ~
        <el-date-picker v-model="endDate" type="date" placeholder="结束日期"  style="width:100%;" ></el-date-picker>
        <el-select v-model="selectComponentValue" clearable placeholder="请选择统计结果" class="selectComponentValue" >
            <el-option
                v-for="item in selectComponentArray"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
        </el-select>
        <el-input v-model="searchOriginOrderNo" class="order_search_origin_no" placeholder="请输入原始订单号" />
        <el-button type="warning" plain @click="searchOrderList" class="riqisubmit">查询</el-button>
        <el-button type="primary"  @click="exportOrderList" class="riqisubmit" v-bind:disabled="this.orderList.length==0">导出订单数据表</el-button>
        <el-button type="danger" @click="deleteAllOrder" class="delete_button">一键删除订单数据</el-button>
    </div>
    <!-- --------------------------------------------------------------------tab---------------------------------------------------------------------------------------------- -->

    <div>
        <el-dialog v-model="dialogFormVisible" title="更新订单统计结果">
            <div style="color: red;margin-top:-20px">*注:编辑时原始编号不可以修改</div>
            <el-form>
                <el-form-item label="原始编号" :label-width="formLabelWidth">
                    <el-input autocomplete="off" v-model="orderAddVO.originOrderNo" placeholder="原始编号"
                        v-bind:readonly="orderAddVO.id != null" />
                </el-form-item>
            </el-form>
            <el-form>
                <el-form-item label="统计结果" :label-width="formLabelWidth">
                    <el-select v-model="orderAddVO.statisticalResults" clearable placeholder="请选择统计结果" class="selectComponentValue">
                        <el-option
                            v-for="item in selectComponentArray"
                            :key="item.label"
                            :label="item.label"
                            :value="item.label"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancellation">取消</el-button>
                    <el-button type="primary" @click="updateOrderStatisticalResults">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <div class="v-table" ref="tableheight" style="width: 100%; height:650px">
            <el-table :data="orderList" style="width:100%; height:600px" border stripe>
                <el-table-column lable="序号" type="index" width="50" fixed>
                </el-table-column>
                <el-table-column label="原始编号" width="260" fixed>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span class="span1">{{ scope.row.originOrderNo }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="订单编号" width="260" fixed>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.orderNo }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="省份" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.province }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="交易状态" width="90" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.tradeStatus }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="付款时间" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.payDate }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="网店名称" width="160" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.storeName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="商品名称" width="320" class="xishu" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.productName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="60" class="xishu">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.productNum }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="明细金额" width="100" class="xishu">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.orderPrice }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="推广链接" width="400" class="xishu" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.promotionLink }}</span>
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="二级页" width="220" class="xishu" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.secondaryPage }}</span>
                        </div>
                    </template>
                </el-table-column> -->
                <el-table-column label="分销" width="180" class="xishu" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.distribution }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="统计结果" width="100" class="xishu" show-overflow-tooltip>
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.statisticalResults }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="非节目时间销量或分销" width="100" class="xishu">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.extend1 }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="修改信息">
                    <template #default="scope">
                        <el-button type="primary" size="small"
                            @click="handleEdit(scope.$index, scope.row.id)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <div class="block-box">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[1, 5, 10,20]" :page-size="pageSize" :total="total"
                    layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
    
<script>
import axios from '../api/index'
import { ElLoading } from 'element-plus';
import loading from '../api/loading'
export default {
    data() {
        return {
            dialogFormVisible: false, //控制编辑弹窗显示的变量
            startDate: '',
            endDate: '',
            searchOriginOrderNo:'', //查询原始订单号
            orderList: [],
            currentPage: 1, // 当前页码
            pageSize: 20, // 每页的数据条数
            total: 0, // 总条数
            selectComponentArray: [], // 下拉框的数组
            selectComponentValue: 1, //下拉框选中的值
            orderAddVO: {
                originOrderNo: '',//原始订单编号
                statisticalResults: '',//订单打标签结果
                id: ''//订单主
            },
        }
    },
    methods: {
        // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
        beforeUploadFile(file) {
            console.log('before upload')
            console.log(file)
            let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
            let size = file.size / 1024 / 1024
            if (extension !== 'xlsx') {
                this.$message.warning('只能上传后缀是.xlsx的文件')
            }
            if (size > 1024) {
                this.$message.warning('文件大小不得超过1G')
            }
        },
        // 上传
        upload(param) {
            this.$refs.upload.clearFiles(); //去掉文件列表 
            let  loadingInstance = ElLoading.service({
                fullscreen: true,
                lock: true,
                text: "订单数据正在上传，请耐心等待",
                background: "rgba(0, 0, 0, 0.7)"
                });
            //const formData = new FormData()
            //formData.append('file', param.file)
            axios.postRequest('/order/importOrderExcelData', param.file)
                .then(res => {
                    if (res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '订单数据导入成功,请使用'
                        })
                        this.searchOrderList()
                    } else {
                        this.$message({
                            type: 'error',
                            message: '文件上传或导入失败!'+res.data.message
                        })
                    }
                    setTimeout(() => {
                                loadingInstance.close();//我们的获取接口数据函数
                                }, 2000);
                })
                .catch(err => {
                    this.$message({
                        type: 'error',
                        message: '文件上传或导入失败!'
                    })
                })
        },
        searchOrderList() {
            //var pageInfo = { startDate: minToday, endDate: maxToday, pageNum: this.currentPage, pageSize: this.pageSize }
            var searchInfo = { 
                startDate: this.startDate, 
                endDate: this.endDate, 
                pageNum: this.currentPage, 
                pageSize: this.pageSize,
                type: this.selectComponentValue,
                originOrderNo: this.searchOriginOrderNo
            }
            axios.postRequest('/order/searchOrderList', searchInfo)
                .then(res => {
                    if (res.data.code === 200) {
                        this.orderList = res.data.data.orderVOList
                        //注意：分页这里必须要将total转换成数字！！！
                        this.total = parseInt(res.data.data.total)                      
                        // this.startDate = minToday
                        // this.endDate = maxToday
                    }
                })
        },
        //编辑查询方法------
        handleEdit(index, row) {
            this.dialogFormVisible = true
            // 调ajax后台详情接口(id)
            let base = `/order/searchOrderById/${row}`
            axios.getRequest(base)
                .then((res) => {
                    if (res.data.code === 200) {
                        this.orderAddVO.originOrderNo = res.data.data.originOrderNo
                        this.orderAddVO.statisticalResults = res.data.data.statisticalResults
                        this.orderAddVO.id = row
                    } else {
                        this.$message({
                            type: 'error',
                            message: '查询订单数据失败！'+res.data.message
                        })
                    }
                })

        },
        // 更新订单的统计结果(打的标签)
        updateOrderStatisticalResults(){
            axios.postRequest('/order/updateOrderStatisticalResults', this.orderAddVO)
                .then(res => {
                    if (res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '操作成功！'
                        })
                        this.searchOrderList()
                    } else {
                        this.$message({
                            type: 'error',
                            message: '操作失败！'+res.data.message
                        })
                    }
                })
            this.cancellation()
        },
        cancellation() {
            this.dialogFormVisible = false
            this.orderAddVO.originOrderNo = ''
            this.orderAddVO.statisticalResults = ''
            this.orderAddVO.id = ''
        },
        keyDown(e){
            if (e.key == 'Enter') {
                console.log('回车事件被执行')
                this.searchOrderList()
            }
        },

        exportOrderList(){    
            var pageInfo = {startDate:this.startDate,endDate:this.endDate}
            axios.postRequest('/order/export',pageInfo,'blob')
                 .then(res =>{
                    console.log("导出成功")
                    this.downloadFile(res,'订表数据表生成.xlsx')
                 })
        },
        //监听 pagesize 改变的事件
        handleSizeChange(newSize) {
            console.log(newSize + '+++++++++++++++++');
            this.pageSize = newSize;//重新指定每页数据量
            this.searchOrderList();//带着新的分页请求获取数据
        },
        //监听 页码值 改变的事件
        handleCurrentChange(newPage) {
            console.log(newPage + '-----------------');
            this.currentPage = newPage;//重新指定当前页
            this.searchOrderList();//带着新的分页请求获取数据
        },
        generateOrderReport(type){
          let  loadingInstance = ElLoading.service({
                fullscreen: true,
                lock: true,
                text: "报表数据正在导出，请耐心等待",
                background: "rgba(0, 0, 0, 0.7)"
                });
            console.log("type==="+type)
            var param = {startDate:this.startDate,endDate:this.endDate,type:type}
            axios.postRequest('/order/generateReport',param,'blob')
                .then(res =>{
                    console.log("导出成功")
                    if(type ===1){
                        this.downloadFile(res,'主品报表.xlsx')
                    }
                    if(type === 2){
                        this.downloadFile(res,'媒体销量表.xlsx')
                    }
                    if(type === 3){
                        this.downloadFile(res,'每日飘线及合计销量表.xlsx')
                        // var param = {startDate:this.startDate,endDate:this.endDate}
                        // axios.postRequest('/detail/getDetailNumberReport',param,'blob')
                        //     .then(res =>{
                        //         console.log("导出成功")
                        //         this.downloadFile(res,'每日飘线及合计销量表.xlsx')
                        // })
                    }
                    if(type === 4){          
                    }

                    
                    setTimeout(() => {
                        loadingInstance.close();//我们的获取接口数据函数
                    }, 3000);
                })
        },        
        //下载文件
        downloadFile(res, fileName) {
            let blob = new Blob([res.data]); //res为从后台返回的数据
            //let blob = new Blob([res]); 
            if (!fileName) {
                fileName = res.headers['content-disposition'].split('filename=').pop();
            }
            if ('msSaveOrOpenBlob' in navigator) {
                window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
                const elink = document.createElement('a');
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href);
                document.body.removeChild(elink);
            }
        },
        deleteAllOrder() {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var date = new Date(this.startDate);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h = h < 10 ? ('0' + h) : h;
                var min = date.getMinutes();
                min = min < 10 ? ('0' + min) : min;
                var s = date.getSeconds();
                s = s < 10 ? ('0' + s) : s;
                let searchStartDate = y + '-' + m + '-' + d

                //-----------------------------------------------------------------------------------
                var date = new Date(this.endDate);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h = h < 10 ? ('0' + h) : h;
                var min = date.getMinutes();
                min = min < 10 ? ('0' + min) : min;
                var s = date.getSeconds();
                s = s < 10 ? ('0' + s) : s;
                let searchEndDate = y + '-' + m + '-' + d
                console.log(searchStartDate + '---------' + searchEndDate)
                var pageInfo = {searchStartDate:searchStartDate,searchEndDate:searchEndDate}
                axios.getRequest(`/order/deleteOrderByPaydate/${searchStartDate}/${searchEndDate}`)
                    .then( res => {
                                this.searchOrderList()
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                    })

            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
      }
    },
    mounted() {
        var today = new Date();
        // 获取前一天的日期
        today.setDate(today.getDate() - 1);
        var year = today.getFullYear();//获取年份
        var month = today.getMonth() + 1;//获取月份
        var day = today.getDate();//获取日期
        var minToday = year + "-" + month + "-" + day + " " + "00:00:00";
        var maxToday = year + "-" + month + "-" + day + " " + "23:59:59";
        //var minToday = year + "-" + month + "-" + day;
        //var maxToday = year + "-" + month + "-" + day;
        this.startDate = minToday
        this.endDate = maxToday
        this.searchOrderList()
        window.addEventListener("keydown", this.keyDown);
        this.selectComponentArray = [
            {
                value: 1,
                label: '主品',
            },
             {
                value: 4,
                label: '400飘线',
            },
            {
                value: 5,
                label: '主品监控飘线',
            },
            {
                value: 7,
                label: '历史飘线',
            },
            {
                value: 8,
                label: '爱听团队',
                //label: '爱听',
            },
            {
                value: 9,
                label: '纯飘线',
            },
            {
                value: 10,
                label: '二级页',
            },
            {
                value: 11,
                label: '分销',
            },
            {
                value: 16,
                label: '咏礼记团队',
            }
        ]
    },
    destroyed() {        
         // 销毁事件
      window.addEventListener("keydown", this.keyDown);
    }
}
</script>
    
<style>
.font {
    width: 120px;
    font-size: 13px;
    margin-top: 20px;
    margin-left: 5px;
    height: 20px;
}

.file {
    display: flex; 
}
.filea{
    display:flex;
}
.riqi1 {
   margin-top: 14px;
   margin-left: 5px;
    font-size: 14px;
    display:flex;
    /*padding-left: 25%;*/
    width: 1200px;
    height: 50px;
    line-height: 28px;
}
.riqi1 el-select {
     font-size: 14px;
     display:flex;
     padding-left: 25%;
     height: 50px;
     line-height: 28px;
 }



.daochu1,.daochu2,.daochu3{
   margin-left: 1%;
}

.cell {
    width: 350px;
    text-align: left;
}
.block-box {
    width: 100%;
    height: 50px;
    margin-top: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-pagination {
    height: 80px;
    align-items: center;

}
.daochu {
    margin-top: 14px;
    margin-left: 10%; 
    display: flex;
}
.shangchuan {
    padding-top: 6px;
    margin-top: 8px;
}
.demo-ruleForm{
    width: 0px;
    margin-left: -90px;
    margin-top: 6px;
}
.riqisubmit{
    margin-left: 10px;
    margin-top: -0.2%;
}
.selectComponentValue{
    margin-left: 10px;
    /*margin-top: -0.2%;*/
    width:100%;
}
.order_search_origin_no{
    margin-left:20px;
    line-height: 28px;
    height: 32px;
}
.delete_button{
    margin-top: -0.2%;
}
</style>